﻿var baiduMapTemplate =
    '<div class="panel panel-danger panel-success modalwindow locationselector" style="width: 650px">' +
        '    <div class="panel-heading">地理位置选择</div>' +
        '    <div class="panel-body" style="padding:0px;">' +
        '        <div class="panel panel-default" style="margin-bottom: 0px">' +
        '            <div class="panel-heading" style="border-radius:0px;padding: 5px 20px;">' +
        '                <div class="form-group">' +
        '                    <label class="col-sm-2 control-label" style="margin-top: 6px;">搜索:</label>' +
        '                    <div class="col-sm-10">' +
        '                        <input type="text" id="txtAutoComplete_bmap" style="width:100%;" class="form-control input-sm mapAutoComplete">' +
        '                        <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:200px;height:auto; display:none;z-index: 99999;"></div>' +
        '                    </div>' +
        '                </div>' +
        '                <div class="clearfix"></div>' +
        '            </div>' +
        '            <div class="panel-body mapContrainer" id="mapContrainer" style="padding:5px;height: 450px;">' +
        '            </div>' +
        '        </div>' +
        '    </div>' +
        '    <div class="panel-footer center-block">' +
        '        <button class="btn btn-default pull-right btnCancel" style="margin-left: 20px" type="button">取消</button>' +
        '        <button class="btn btn-primary pull-right btnOK" type="button">确定</button>' +
        '        <div class="clearfix"></div>' +
        '    </div>' +
        //'    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=NywGUL2jiY4OAwvWMobljHFT8OrHl0sK"></script>' +
        '</div>';

    
    (function ($) {
        /*
         * 选择地理位置点
         *
         * options:{
         *  initPos:{  //初始化位置, 如果传入经纬度,则定位到指定位置,如果传入的是string,则通过反查地址获取位置,再跳转
         *      lat:0,
         *      lng:o
         *  },
         *  onSuccess:function(pos){}, //如果选择了位置,则触发该回调,pos传入的参数为 {lat:0,lng:0 , loc : "116,23"}
         *  poi:[{lat:0,lng:0},{lat:0,lng:0}] , //地图上显示的标记点
         * }
         *
         *
         */
        $.fn.GeoPicker = function (options) {

            var defaultOpt = {
                initPos: null,
                onSuccess: null,
                poi: null
            }

            var opt = $.extend({}, defaultOpt, options);

            var cityName = "";

            function G(id) { 
                return document.getElementById(id);
            }

            function setInitPostion(map, container) {
                WebUIJS.Loading();
                //根据浏览器获取当前位置
                var geolocation = new BMap.Geolocation();
                geolocation.getCurrentPosition(function (r) {
                    WebUIJS.CloseLoading();
                    if (this.getStatus() == '0') {
                        addMarker(r.point, map, container);
                        //alert('您的位置：' + r.point.lng + ',' + r.point.lat);
                    } else {
                        //alert('failed' + this.getStatus());
                        WebUIJS.Msg("无法获取当前位置");
                    }

                },
                    { enableHighAccuracy: true });
            }

            function setAutoComplete(map, container, inputCtrl) {

                //var ac = new BMap.Autocomplete(//建立一个自动完成的对象
                //    {
                //        "input": "txtAutoComplete_bmap",
                //        "location": map
                //    });

                var ac = new BMap.Autocomplete({ "input": G("txtAutoComplete_bmap"), "location": map});

                if (!isPoint(opt.initPos)) {
                    ac.setInputValue(opt.initPos);
                }
                ac.show();

                ac.addEventListener("onhighlight",
                    function (e) { //鼠标放在下拉列表上的事件
                        var str = "";
                        var _value = e.fromitem.value;
                        var value = "";
                        if (e.fromitem.index > -1) {
                            value = _value.province + _value.city + _value.district + _value.street + _value.business;
                        }
                        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                        value = "";
                        if (e.toitem.index > -1) {
                            _value = e.toitem.value;
                            value = _value.province + _value.city + _value.district + _value.street + _value.business;
                        }
                        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;


                        G("searchResultPanel").innerHTML = str;
                    });

                //var myValue;
                ac.addEventListener("onconfirm",
                    function (e) { //鼠标点击下拉列表后的事件
                        var _value = e.item.value;
                        var myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                        G("searchResultPanel").innerHTML =
                            "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

                        setPlace(myValue, map, container);
                    });

                $(inputCtrl).keydown(function (event) {

                    if (event.which == 13) {
                        event.preventDefault();

                        var results = ac.getResults();

                        if (results.getNumPois() <= 0) {
                            return;
                        }

                        var poi = results.getPoi(0);

                        var myValue = poi.province + poi.city + poi.district + poi.street + poi.business;

                        $(inputCtrl).val(myValue);

                        G("searchResultPanel").innerHTML = "onconfirm<br />index = 0 <br />myValue = " + myValue;

                        setPlace(myValue, map, container, function () { WebUIJS.Toast('查找不到地点',"error")});
                    }

                });

                return ac;
            }

            function addMarker(point, map, container) {
                map.clearOverlays(); //清除地图上所有覆盖物

                map.centerAndZoom(point, 15);

                var marker = new BMap.Marker(point);
                marker.enableDragging();
                marker.addEventListener("dragend",
                    function (e) {
                        //alert("当前位置：" + e.point.lng + ", " + e.point.lat);
                    });

                map.addOverlay(marker); //添加标注

                container.data("marker", marker);

                return marker;
            }

            function setPlace(keyword, map, container, onFaild) {

                var local = new BMap.LocalSearch(map,
                    { //智能搜索
                        onSearchComplete: myFun,
                        renderOptions: { map: map, autoViewport: true }
                    });

                local.enableAutoViewport();
                local.setMarkersSetCallback(function(poi) {
                    debugger;
                    for (var i = 0; i < poi.length; i++) {
                        var item = poi[i];

                        var m = item.marker;
                        m.addEventListener("click",function () {
                            //var old = $(".locationselector").data("marker");

                            //if (old) {
                            //    map.removeOverlay(old);
                            //}

                            addKeyPoint(map, m.getPosition());

                            //$(".locationselector").data("marker", addMarker(, map, container));
                        });
                    }
                });

                function myFun() {

                    var results = local.getResults();

                    if (results.getNumPois() <= 0) {
                        if (onFaild != undefined && $.isFunction(onFaild)) {
                            onFaild();
                        }

                        return;
                    }

                    //var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果

                    map.clearOverlays();

                    //$(".locationselector").data("marker", addMarker(pp, map, container));
                }

                local.search(keyword, { forceLocal: false });
            }

            function isPoint(str) {
                if (isObject(str)) {
                    if (str.lng != undefined && str.lng != null && str.lat != undefined && str.lat != null) {
                        return true;
                    }
                } else if (isString(str)) {
                    var s = str.split(',');

                    if (s.length == 2) {
                        try {
                            if (parseFloat(s[0]) !== NaN && parseFloat(s[1]) !== NaN) {
                                return true;
                            }

                        } catch (e) {
                            return false;
                        }

                    }

                }

                return false;
            }

            function toPoint(str) {
                if (isPoint(str)) {
                    if (isObject(str)) {
                        return str;
                    } else {
                        if (isString(str)) {
                            var s = str.split(',');

                            if (s.length === 2) {
                                try {
                                    var v = new BMap.Point(parseFloat(s[0]), parseFloat(s[1]));


                                    return v;
                                } catch (e) {
                                    return null;
                                }

                            }
                        }
                    }
                }
                return null;
            }

            function addKeyPoint(map, point) {
                var old = $(".locationselector").data("marker");

                if (old) {
                    map.removeOverlay(old);
                }

                var marker = new BMap.Marker(new BMap.Point(point.lng, point.lat)/*new BMap.Point(e.point.lng, e.point.lat)*/); // 创建点
                marker.enableDragging();

                map.addOverlay(marker); //增加点
                marker.setZIndex(9999999);
                marker.setAnimation(BMAP_ANIMATION_BOUNCE);


                $(".locationselector").data("marker", marker);
            }

            function initMap() {
                var el = $(baiduMapTemplate);
                $(document).find("body").append(el);
                var auto;

                WebUIJS.ModalByElement(el,
                    function (modal) {
                        $(modal).find('.locationselector').each(function () {
                            var $this = $(this);
                            var map = new BMap.Map("mapContrainer");

                            var myCity = new BMap.LocalCity();
                            myCity.get(function (result) {
                                cityName = result.name;
                                map.setCurrentCity(result.name);
                            });

                            if (isObject(opt.initPos)) {
                                opt.initPos = new BMap.Point(opt.initPos.lng, opt.initPos.lat);
                                map.centerAndZoom(toPoint(opt.initPos), 12);   
                            }
                            else if (!opt.initPos) {
                                var myCity = new BMap.LocalCity();
                                myCity.get(function (result) {
                                    cityName = result.name;
                                    map.centerAndZoom(result.center, 12);   
                                });

                            }
                            
                            //map.centerAndZoom(toPoint(options.initPos), 12);                   // 初始化地图,设置城市和地图级别。

                            $(this).data("bmap", map);
                            $(this).data("marker", null);

                            map.enableScrollWheelZoom();
                            //var initPos = toPoint(options.InitPos)

                            if (isPoint(opt.initPos)) {
                                initMarker = addMarker(toPoint(opt.initPos), map, $this);
                            } else if (isString(opt.initPos) && opt.initPos.length > 4) {
                                setPlace(opt.initPos,
                                    map,
                                    $this,
                                    function () {
                                        WebUIJS.Alert("找不到输入的地址所对应的地理位置,当前地图将定位到本机所在GPS");
                                        setInitPostion(map, $this);
                                    });
                                //$(this).find('.mapAutoComplete').val(initPos);

                            } else {
                                setInitPostion(map, $this);
                            }

                            if (opt.poi && opt.poi.length > 0) {
                                for (var i = 0; i < opt.poi.length; i++) {
                                    var point = opt.poi[i];
                                    addMarker(point, map, $this);
                                }
                            }

                            auto=setAutoComplete(map, $this, $(this).find('.mapAutoComplete'));

                            map.addEventListener("click",
                                function (e) {
                                    addKeyPoint(map, new BMap.Point(e.point.lng, e.point.lat));

                                    //var old = $(".locationselector").data("marker");

                                    //if (old) {
                                    //    map.removeOverlay(old);
                                    //}


                                    ////map.clearOverlays(); //清除地图上所有覆盖物

                                    //var marker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat)); // 创建点
                                    //marker.enableDragging();

                                    //map.addOverlay(marker); //增加点

                                    //$this.data("marker", marker);
                                });


                            map.addEventListener("zoomstart",
                                function () {
                                    $this.data("currentcenterpoint", map.getCenter());
                                });

                            map.addEventListener("zoomend",
                                function (type, target) {
                                    map.panTo($this.data("currentcenterpoint"));
                                });

                            $(this).find('.btnOK').click(function () {
                                var marker = $this.data("marker");

                                if (marker == null) {
                                    WebUIJS.Msg("请选择地理位置");
                                } else {
                                    var pos = marker.getPosition();

                                    layer.close($(this).parents(".layui-layer").data('layerindex'));

                                    if (opt.onSuccess) {
                                        opt.onSuccess({ lng: pos.lng, lat: pos.lat, loc: pos.lng + "," + pos.lat});
                                    }
                                }

                                auto.dispose();

                                map.clearOverlays();
                                $(el).remove();
                            });

                            $(this).find(".btnCancel").click(function () {
                                layer.close($(this).parents(".layui-layer").data('layerindex'));
                                map.clearOverlays();
                                auto.dispose();
                                $(el).remove();
                                
                            });
                        });
                    },
                    function (layerIndex) {
                        auto.dispose();
                        $(el).remove();
                    }
                );
            }

            if (typeof BMap === 'undefined' || BMap === null || typeof BMap.Map === 'undefined' || BMap.Map === null) {
                WebUIJS.Loading(); //动态加载百度的脚本

                var script = document.createElement("script");
                script.src = "http://api.map.baidu.com/api?v=2.0&ak=NywGUL2jiY4OAwvWMobljHFT8OrHl0sK&callback=InitializeBMap";
                document.body.appendChild(script);

                window.loadingBMapHandler=null;

                window.loadingBMapHandler = setInterval(function () {
                    if (typeof window.BMap !== 'undefined' && window.BMap !== null && typeof BMap.Map !== 'undefined' && BMap.Map !== null) {
                        clearInterval(loadingBMapHandler);
                        initMap();
                        window.loadingBMapHandler = null;
                        WebUIJS.CloseLoading();
                    }
                }, 200);
            } else {
                initMap();
            }

        }

        /*
         * 使用腾讯地图,选择地理位置点
         *
         * options:{
         *  initPos:{  //初始化位置, 如果传入经纬度,则定位到指定位置,如果传入的是string,则通过反查地址获取位置,再跳转
         *      lat:0,
         *      lng:o
         *  },
         *  onSuccess:function(pos){}, //如果选择了位置,则触发该回调,pos传入的参数为 {lat:0,lng:0}
         *  poi:[{lat:0,lng:0},{lat:0,lng:0}] , //地图上显示的标记点
         * }
         *
         *
         */
        $.fn.TencentGeoPicker = function(options) {
            var defaultOpt = {
                initPos: null,
                onSuccess: null,
                poi: null
            }

            var cityName = "";
            var markers = [];

            var opt = $.extend({}, defaultOpt, options);

            function setAutoComplete(map, container, inputCtrl) {

                //var ac = new BMap.Autocomplete(//建立一个自动完成的对象
                //    {
                //        "input": "txtAutoComplete_bmap",
                //        "location": map
                //    });

                var ap = new qq.maps.place.Autocomplete(document.getElementById('txtAutoComplete_bmap'), {
                    offset: new qq.maps.Size(0, 5),
                    location: '北京市',
                    zIndex: 100000000
                });

                var ac = new BMap.Autocomplete({ "input": G("txtAutoComplete_bmap"), "location": map });

                if (!isPoint(opt.initPos)) {
                    ac.setInputValue(opt.initPos);
                }
                ac.show();

                ac.addEventListener("onhighlight",
                    function (e) { //鼠标放在下拉列表上的事件
                        var str = "";
                        var _value = e.fromitem.value;
                        var value = "";
                        if (e.fromitem.index > -1) {
                            value = _value.province + _value.city + _value.district + _value.street + _value.business;
                        }
                        str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                        value = "";
                        if (e.toitem.index > -1) {
                            _value = e.toitem.value;
                            value = _value.province + _value.city + _value.district + _value.street + _value.business;
                        }
                        str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;


                        G("searchResultPanel").innerHTML = str;
                    });

                //var myValue;
                ac.addEventListener("onconfirm",
                    function (e) { //鼠标点击下拉列表后的事件
                        var _value = e.item.value;
                        var myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                        G("searchResultPanel").innerHTML =
                            "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

                        setPlace(myValue, map, container);
                    });

                $(inputCtrl).keydown(function (event) {

                    if (event.which == 13) {
                        event.preventDefault();

                        var results = ac.getResults();

                        if (results.getNumPois() <= 0) {
                            return;
                        }

                        var poi = results.getPoi(0);

                        var myValue = poi.province + poi.city + poi.district + poi.street + poi.business;

                        $(inputCtrl).val(myValue);

                        G("searchResultPanel").innerHTML = "onconfirm<br />index = 0 <br />myValue = " + myValue;

                        setPlace(myValue, map, container, function () { WebUIJS.Toast('查找不到地点', "error") });
                    }

                });

                return ac;
            }

            function addMarker(point, map, container) {
                map.clearOverlays(); //清除地图上所有覆盖物

                map.centerAndZoom(point, 15);

                var marker = new qq.maps.Marker({
                    map: map,
                    position: point
                });

                marker.addEventListener("dragend",
                    function (e) {
                        //alert("当前位置：" + e.point.lng + ", " + e.point.lat);
                    });

                markers.push(marker);

                //container.data("marker", marker);

                return marker;
            }

            function setPlace(keyword, map, container, onFaild) {
                var latlngBounds = new qq.maps.LatLngBounds();
                var local = new qq.maps.SearchService(
                    { //智能搜索
                        complete: myFun,
                        location: keyword,
                        map: map
                    });

                function myFun(results) {

                    var pois = results.detail.pois;

                    if (pois.length <= 0) {
                        if (onFaild != undefined && $.isFunction(onFaild)) {
                            onFaild();
                        }

                        return;
                    }

                    for (var i = 0; i < markers.length; i++) {
                        markers[i].setMap(null);
                    }

                    for (var j = 0; j < pois.length; j++) {
                        var poi = pois[i];
                        latlngBounds.extend(poi.latLng);

                        var marker = addMarker(poi.latLng, map);

                        markers.push(marker);

                        marker.addEventListener("click", function () {
                            //var old = $(".locationselector").data("marker");

                            //if (old) {
                            //    map.removeOverlay(old);
                            //}

                            addKeyPoint(map, marker.getPosition());

                            //$(".locationselector").data("marker", addMarker(, map, container));
                        });
                    }

                    map.fitBounds(latlngBounds);

                    map.clearOverlays();
                }

                local.search(keyword);
            }

            function isPoint(str) {
                if (isObject(str)) {
                    if (str.lng != undefined && str.lng != null && str.lat != undefined && str.lat != null) {
                        return true;
                    }
                } else if (isString(str)) {
                    var s = str.split(',');

                    if (s.length == 2) {
                        try {
                            if (parseFloat(s[0]) !== NaN && parseFloat(s[1]) !== NaN) {
                                return true;
                            }

                        } catch (e) {
                            return false;
                        }

                    }

                }

                return false;
            }

            function toPoint(str) {
                if (isPoint(str)) {
                    if (isObject(str)) {
                        return str;
                    } else {
                        if (isString(str)) {
                            var s = str.split(',');

                            if (s.length === 2) {
                                try {
                                    var v = new TMap.LatLng(parseFloat(s[1]),parseFloat(s[0]));


                                    return v;
                                } catch (e) {
                                    return null;
                                }

                            }
                        }
                    }
                }
                return null;
            }

            function addKeyPoint(map, point) {
                var old = $(".locationselector").data("marker");

                if (old) {
                    old.setMap(null);
                }

                var marker = new qq.maps.Marker({
                    position: point,
                    map: map
                });

                //var marker = new BMap.Marker(new BMap.Point(point.lng, point.lat)/*new BMap.Point(e.point.lng, e.point.lat)*/); // 创建点
                //marker.enableDragging();
                marker.setAnimation(qq.maps.MarkerAnimation.DOWN);
                marker.setDraggable(true);

                $(".locationselector").data("marker", marker);

                return marker;
            }

            function initMap() {
                var el = $(baiduMapTemplate);
                $(document).find("body").append(el);
                var auto;

                WebUIJS.ModalByElement(el,
                    function (modal) {
                        $(modal).find('.locationselector').each(function () {
                            var $this = $(this);


                            var map = new qq.maps.Map(document.getElementById("mapContrainer"), {
                                zoom: 8,
                                center: new qq.maps.LatLng(opt.initPos.lat, opt.initPos.lng),
                                mapTypeId: qq.maps.MapTypeId.ROADMAP
                            });

                            var myCity = new BMap.LocalCity();
                            myCity.get(function (result) {
                                cityName = result.name;
                                map.setCurrentCity(result.name);
                            });

                            if (isObject(opt.initPos)) {
                                opt.initPos = new TMap.LatLng(opt.initPos.lat,opt.initPos.lng);
                                map.setCenter(toPoint(opt.initPos), 12);
                            }
                            else if (!opt.initPos) {

                                var myCity = new qq.maps.CityService();

                                myCity.setComplete(function (results) {
                                    cityName = results.detail.name;

                                    map.setCenter(results.detail.latLng);
                                });

                                myCity.searchLocalCity();
                            }

                            //map.centerAndZoom(toPoint(options.initPos), 12);                   // 初始化地图,设置城市和地图级别。

                            $(this).data("bmap", map);
                            $(this).data("marker", null);

                            //map.enableScrollWheelZoom();
                            //var initPos = toPoint(options.InitPos)

                            if (isPoint(opt.initPos)) {
                                addKeyPoint(toPoint(opt.initPos), map, $this);
                            } else if (isString(opt.initPos) && opt.initPos.length > 4) {
                                setPlace(opt.initPos,
                                    map,
                                    $this,
                                    function () {
                                        WebUIJS.Alert("找不到输入的地址所对应的地理位置,当前地图将定位到本机所在GPS");
                                        setInitPostion(map, $this);
                                    });
                                //$(this).find('.mapAutoComplete').val(initPos);

                            } else {
                                setInitPostion(map, $this);
                            }

                            if (opt.poi && opt.poi.length > 0) {
                                for (var i = 0; i < opt.poi.length; i++) {
                                    var point = opt.poi[i];
                                    addMarker(new TMap.LatLng(point.lat,point.lng), map, $this);
                                }
                            }

                            auto = setAutoComplete(map, $this, $(this).find('.mapAutoComplete'));

                            map.addEventListener("click",
                                function (e) {
                                    addKeyPoint(map, new TMap.LatLng(e.latLng.getLat(), e.latLng.getLng()));
                                });


                            map.addEventListener("idle",
                                function () {
                                    $this.data("currentcenterpoint", map.getCenter());
                                });

                            map.addEventListener("dragend",
                                function (type, target) {
                                    map.panTo($this.data("currentcenterpoint"));
                                });

                            $(this).find('.btnOK').click(function () {
                                var marker = $this.data("marker");

                                if (marker == null) {
                                    WebUIJS.Msg("请选择地理位置");
                                } else {
                                    var pos = marker.getPosition();

                                    layer.close($(this).parents(".layui-layer").data('layerindex'));

                                    if (opt.onSuccess) {
                                        opt.onSuccess({ lng: pos.getLng(), lat: pos.getLat() });
                                    }
                                }

                                auto.dispose();

                                map.clearOverlays();
                                $(el).remove();
                            });

                            $(this).find(".btnCancel").click(function () {
                                layer.close($(this).parents(".layui-layer").data('layerindex'));
                                map.clearOverlays();
                                auto.dispose();
                                $(el).remove();

                            });
                        });
                    },
                    function (layerIndex) {
                        auto.dispose();
                        $(el).remove();
                    }
                );
            }

            if (typeof qq.maps.Map === 'undefined' || qq.maps.Map === null || typeof qq.maps.Map === 'undefined' || qq.maps.Map === null) {
                WebUIJS.Loading(); //动态加载腾讯的脚本

                var script = document.createElement("script");
                script.src = "https://map.qq.com/api/js?v=2.exp&key=QUDBZ-RXZL5-ASJIL-Q2KGM-CYNHF-SHBXI&callback=InitializeBMap";
                document.body.appendChild(script);

                window.loadingBMapHandler = null;

                window.loadingBMapHandler = setInterval(function () {
                    if (typeof qq.maps.Map !== 'undefined' && qq.maps.Map !== null && typeof qq.maps.Map !== 'undefined' && qq.maps.Map !== null) {
                        clearInterval(loadingBMapHandler);
                        initMap();
                        window.loadingBMapHandler = null;
                        WebUIJS.CloseLoading();
                    }
                }, 200);
            } else {
                initMap();
            }
        }
})(jQuery);


function InitializeBMap() {
    
}